using UnityEngine;
using System.Collections;

[System.Serializable]
public class Inventory1 : MonoBehaviour {
	
	public Texture background;
	public Texture cellDefault;
	public Texture cellHover;
	public Texture cellClick;
	public MouseLook[] mouseLookScripts;	
	public Item[] items;
	
	private bool showInventory = false;
	private int columns = 0;
	private int rows = 0;
	
	private int inCell = -1;
	private bool inACell = false;
	
	// Use this for initialization
	void Start () {
		columns = Game.game.getInventoryColumns();
		rows = Game.game.getInventoryRows();
		items = new Item[columns*rows];
		
		Game.inventory = this;
		
		Debug.Log("Columns: " + columns);
		Debug.Log("Rows: " + rows);
	}
	
	// Update is called once per frame
	void Update () {
		if (Input.GetKeyUp(KeyCode.I)) {
			showInventory = !showInventory;
			Game.game.inventoryShown = showInventory;
			foreach (MouseLook mouseLookScript in mouseLookScripts)  {
				mouseLookScript.enableMouse = !showInventory;
			}
		}
	}
	
	void OnGUI() {
		if (showInventory) {
			inACell = false;
			float width = 64;
			float height = 64;
			float spacing = 4;
			
			float boxWidth = (width*columns)+(spacing*columns);
			float boxHeight = (height*rows)+(spacing*rows);
			float boxLeft = (16);
			float boxTop = (128);
			
			//GUI.Box(new Rect(boxLeft-32, boxTop-32, boxWidth+64, boxHeight+64), "");
			GUI.DrawTexture(new Rect(boxLeft-32, boxTop-32, boxWidth+64, boxHeight+64), background);
			
			Rect mouseRec = new Rect(Input.mousePosition.x, Screen.height-Input.mousePosition.y, 16, 16);
			Vector3 mousePos = new Vector3(Input.mousePosition.x, Screen.height-Input.mousePosition.y, Input.mousePosition.z);
			
			int cell = 0;
			int itemCount = 0;
			for (int i = 0; i < rows; i++) {
				for (int j = 0; j < columns; j++) {
					float left = boxLeft+(width*j)+(spacing*j);
					float top = boxTop+(height*i)+(spacing*i);
					Rect cellRec = new Rect(left, top, width, height);
					
					if (items[cell] != null) {
						GUI.DrawTexture(cellRec, items[cell].icon);						
						itemCount++;
					}
					GUI.DrawTexture(cellRec, cellDefault);
					if (cellRec.Contains(mousePos)) {
						if (Input.GetMouseButton(0)) {
							GUI.DrawTexture(cellRec, cellClick);
							if (items[cell] != null) {
								items[cell].onLeftClick();	
							}
						} else {
							GUI.DrawTexture(cellRec, cellHover);	
						}
						inCell = cell;
						inACell = true;
					}
					cell++;
				}
			}
						
			if (items != null && inCell > -1) {
				if (items[inCell] != null && inACell) {							
					GUI.Label(new Rect(mousePos.x, mousePos.y, 1000, 512), items[inCell].name + "\n" + items[inCell].description);	
				}
			}
		}
	}
}
